import { Router } from 'vue-router'
import NProgress from 'nprogress'
import { getAsyncRoutesOfRole } from '@/utils/routes'
import { useUserStore } from '@/store'
import { useSession, useAsyncRoute } from '@/hooks'
import { setPageTitle } from '@/utils'
import { find } from '@/utils/routes'

export let isLoadedAsyncRoutes = false

const { getAuthInfo } = useSession()

const WhiteListOfPath = ['/learn', '/map', '/login']
const { asyncAddRoutes } = useAsyncRoute()

export function beforeGuard(router: Router) {
  router.beforeEach(async (to) => {
    NProgress.start()
    setPageTitle(to.meta.title as string)

    const session = getAuthInfo()
    const mainStore = useUserStore()

    if (session.token) {
      if (to.path === '/login') {
        return '/home'
      } else {
        if (!isLoadedAsyncRoutes) {
          try {
            const pcRoutes = await getAsyncRoutesOfRole()
            mainStore.addRoutesOfRoles(pcRoutes)
            isLoadedAsyncRoutes = true

            asyncAddRoutes(pcRoutes)
          } catch (error) {
            console.log('getAsyncRoutesOfRole-error ==>', error)
          }

          return to.path
        } else {
          const have = find(mainStore.pcRoutes, to.path)
          return !!have
        }
      }
    } else {
      if (WhiteListOfPath.includes(to.path)) {
        return true
      } else {
        return `/login`
      }
    }
  })
}

export function afterGuard(router: Router) {
  router.afterEach(() => {
    NProgress.done()
  })
}
